package com.demo.myapplication.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.demo.myapplication.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class FileFragment extends Fragment implements View.OnClickListener {
  private static String Tag = FileFragment.class.getSimpleName();

  private Spinner spinner;
  private Button readBtn;

  private ViewPager viewPager;
  private StringBuffer content = new StringBuffer();
  private ArrayList<String> files = new ArrayList<>();

  public static FileFragment newInstance(Bundle args) {
    FileFragment fragment = new FileFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_file, container, false);
    spinner = (Spinner) v.findViewById(R.id.path);
    readBtn = (Button) v.findViewById(R.id.read_btn);
    viewPager = (ViewPager) v.findViewById(R.id.viewPager);
    ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
    viewPager.setOffscreenPageLimit(5);
    viewPager.setAdapter(pagerAdapter);

    loadFileList();

    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, files);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    readBtn.setOnClickListener(this);
    return v;
  }

  private void loadFileList() {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File[] listFiles = path.listFiles();
    if (!path.exists() || listFiles == null) {
      return;
    }
    for (File f : listFiles) {
      if (f.isFile() && f.getName().endsWith(".txt")) {
        files.add(f.getAbsolutePath());
      }
    }
  }

  @Override
  public void onClick(final View v) {
    switch (v.getId()) {
      case R.id.read_btn:
        v.setEnabled(false);
        ((Button) v).setText(R.string.loading);
        final String path = getPath();
        Log.d(Tag, "path=" + path);
        if (TextUtils.isEmpty(path)) {
          Snackbar.make(v, R.string.no_file_path, Snackbar.LENGTH_LONG).show();
          return;
        }
        new Thread(new Runnable() {
          @Override
          public void run() {
            readFileChapterList(path, new ReadCallBackListener() {

              @Override
              public void onFinish() {
                super.onFinish();
                final String time = getTime();
                getActivity().runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    Toast.makeText(getActivity(), "coast " + time + "s", Toast.LENGTH_SHORT).show();
                    loadChapterTitles();
                    v.setEnabled(true);
                    ((Button) v).setText(R.string.read);
                  }
                });
              }
            });
          }
        }).start();
        break;
      default:
        break;
    }
  }

  public String getPath() {
    return (String) spinner.getSelectedItem();
  }

  private class ViewPagerAdapter extends FragmentStatePagerAdapter {

    public ViewPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public Fragment getItem(int position) {
      Bundle args = new Bundle();
      args.putInt(ChapterFragment.EXTRA_POS, position);
      args.putString(ChapterFragment.EXTRA_PATH, getPath());
      Log.d(Tag, "position" + position + ",path=" + getPath());
      return ChapterFragment.newInstance(args);
    }

    @Override
    public int getCount() {
      return chapterTitles.size();
    }
  }

  private void loadChapterTitles() {
    viewPager.getAdapter().notifyDataSetChanged();
    viewPager.setCurrentItem(0);
    //show dialog
    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, chapterTitles);
    new AlertDialog.Builder(getActivity())
        .setTitle(getString(R.string.chapter_list))
        .setAdapter(adapter, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            viewPager.setCurrentItem(which);
          }
        }).show();
  }

  private ArrayList<String> chapterTitles = new ArrayList<>();

  public static String chapterTitlePrefix = "章节名：";

  private void readFileChapterList(final String path, final ReadCallBackListener listener) {
    listener.onBegin();
    FileInputStream fis;
    BufferedReader br = null;
    chapterTitles.clear();
    try {
      fis = new FileInputStream(path);
      br = new BufferedReader(new InputStreamReader(fis, "utf8"));
      String lineStr;
      while ((lineStr = br.readLine()) != null) {
        if (lineStr.startsWith(chapterTitlePrefix) || chapterTitles.size() == 0) {
          chapterTitles.add(lineStr.replace(chapterTitlePrefix, ""));
        }
        lineStr = null;
      }
      listener.onFinish();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (br != null) {
          br.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
